#!/usr/bin/env python
# encoding: utf-8

# Copyright (c) 2009 Klaas Pieter Annema
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import os
import sys
import getopt
import getpass
from datetime import date, datetime

from RTMFetcher.RTMFetcher import RTMFetcher
			
def usage():
	print 'The RTM Fetcher shows tasks matching the option you specifiy. The following options are available:'
	print '-h --help \t\t: Prints this message and exits'
	print '-d --dues \t\t: Show tasks with these due dates'
	print '-t --tags \t\t: Show tasks with these tags'
	print '-p --priorities \t: Shows tasks with these priorities'
	print '-u --username <username>: Your RTM username, this value is mandatory'
	print '--password \t\t: Prompts for your RTM password.'
	print '-s --store \t\t: Stores your RTM password in the keychain.'
	
def main(argv=None):
	
	if argv is None:
		argv = sys.argv

		try:
			opts, args = getopt.getopt(argv[1:], "hd:t:p:u:s ", ['help', 'dues=', 'tags=', 'priorities=', 'username=', 'store', 'password'])
		except getopt.error, msg:
			print msg
			usage()
			
			sys.exit(1)
			
		# Create variables to hold values passed in from the command line
		username = None
		password = None
		
		shouldStore = False
		tags = []
		dues = []
		priorities = []
		
		# Run through all the options and add them to the correct variable
		for option, value in opts:	
			
			# HELP
			if option in ('-h', '--help'):
				usage()
				sys.exit(2)
			
			# TAGS
			if option in ('-t', '--tags'):		
				for tag in value.split(','):
					tags.append(tag.strip())
			
			# DUES
			if option in ('-d', '--dues'):
				
				# Get the current date to offset from
				today = date.today()
				
				for due in value.split(','):
					due = due.strip().lower()
					
					# Determine how much we need to offset from the current date
					if due == 'today':
						dues.append(today)
					
					elif due == 'tomorrow':
						dues.append(today.replace(day=today.day + 1))
					
					else:
						try:
							dues.append(datetime.strptime(due, '%y%m%d').date())
							
						except ValueError, e:
							print 'date \'%s\' is not in YYMMDD format' % due
						
			
			# PRIORITIES
			if option in ('--priorities'):
				for priority in value.split(','):
					try:
						priority = int(priority.strip())
						
						if priority != 0 and priority != 1 and priority != 2 and priority != 3:
							print 'Priority: \'%s\' is not between 0 and 3' % priority	
						
						else:
							priorities.append(priority)
						
					except:
						print 'Priority: \'%s\' is not a numeric value' % priority
						
			# STORE
			if option in ('-s', '--store'):				
				shouldStore = True
				
			# USERNAME
			if option in ('-u', '--username'):
				username = value
				
			# PASSWORD
			if option == '--password':
				password = getpass.getpass("RTM Password:")	
	
	
	if username == None:
		usage()
		return '-u or --username=<username> is mandatory.'
		sys.exit(0)
		
	if shouldStore and password == None:
		print '-s or --store was specified without password. Use --password  to specifiy your password.'
	
	# If everything went well, create the RTM fetcher with all the necesary data
	RTMFetcher(username=username, password=password, shouldStore=shouldStore, dues=dues, tags=tags, priorities=priorities)

if __name__ == '__main__':	
	sys.exit(main())

